import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../extension/index.dart';
import 'index.dart';

/// @Author 杨璐铭
/// @Date 2023/6/3 5:55 PM
/// @describe 输入组件，默认是搜索框样式
class InputWidget extends StatefulWidget {
  const InputWidget({
    Key? key,
    required this.controller,
    required this.hint,
    this.bgPadding,
    this.inputFormatters,
    this.readOnly = false,
    this.fontSize = 12,
    this.fontWeight,
    this.cleanSize,
    this.bgDecoration,
    this.suffix,
    this.trailing,
    this.height,
    this.color,
    this.keyboardType,
    this.suffixMargin,
    this.obscureText = false,
    this.maxLines = 1,
    this.minLines,
    this.showClean = true,
    this.cleanAction,
    this.textInputAction = TextInputAction.search,
    this.textAlign = TextAlign.start,
  }) : super(key: key);

  final InputController controller;
  final EdgeInsetsGeometry? bgPadding;
  final String hint;
  final List<TextInputFormatter>? inputFormatters;
  final bool readOnly;
  final double fontSize;
  final FontWeight? fontWeight;
  final Decoration? bgDecoration;
  final Widget? suffix;
  final Widget? trailing;
  final double? cleanSize;
  final double? height;
  final Color? color;
  final TextInputType? keyboardType;
  final double? suffixMargin;
  final bool obscureText;
  final int? maxLines;
  final int? minLines;
  final bool showClean;
  final void Function()? cleanAction;
  final TextInputAction textInputAction;
  final TextAlign textAlign;

  @override
  State<StatefulWidget> createState() => _InputWidgetState();
}

class _InputWidgetState extends State<InputWidget> {
  late final InputController controller = widget.controller;
  final _showDel = false.obs;

  @override
  void initState() {
    super.initState();

    /// 自动获得焦点
    SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
      if (widget.controller.autoFocus) {
        FocusScope.of(context).requestFocus(widget.controller.focusNode);
      }
    });
    SchedulerBinding.instance.scheduleFrame();
    controller.controller.addListener(_checkShowDel);
  }

  ///是否显示清空按钮
  void _checkShowDel() {
    bool show = controller.controller.text.notEmpty;
    if (_showDel.value != show) _showDel.value = show;
  }

  @override
  Widget build(BuildContext context) {
    return !widget.readOnly
        ? GestureDetector(
            //扩大点击范围
            onTap: () => widget.controller.focusNode.requestFocus(),
            child: buildContent(),
          )
        : buildContent();
  }

  Widget buildContent() {
    return Container(
      height: widget.height,
      decoration: widget.bgDecoration,
      padding: widget.bgPadding ?? EdgeInsets.symmetric(horizontal: 20.w),
      child: Row(
        children: [
          if (widget.suffix != null) ...[
            widget.suffix!.paddingRight(widget.suffixMargin ?? 6.w),
          ],
          Expanded(child: getInput().paddingRight(widget.showClean ? 6.w : 0)),
          if (widget.showClean)
            Obx(() {
              return _showDel.value
                  ? ButtonWidget(
                      onTap: () {
                        controller.cleanInput();
                        _showDel.value = false;
                        if (widget.cleanAction != null) {
                          widget.cleanAction!();
                        }
                      },
                      width: 25.w,
                      height: 25.w,
                      alignment: Alignment.center,
                      hasInkWell: false,
                      // child: SvgPicture.asset(Assets.svgInputClean, width: widget.cleanSize ?? 14.w),
                      child: Icon(Icons.clear, size: widget.cleanSize ?? 14.w),
                    )
                  : const SizedBox.shrink();
            }),
          if (widget.trailing != null) widget.trailing!
        ],
      ),
    );
  }

  Widget getInput() {
    return TextField(
      readOnly: widget.readOnly,
      decoration: InputDecoration(
        border: InputBorder.none,
        hintText: widget.hint,
        hintStyle: TextStyle(color: const Color(0XFF86909C), fontSize: widget.fontSize, fontWeight: FontWeight.normal),
        isCollapsed: true,
      ),
      onChanged: (text) {
        // if (controller.controller.value.isComposingRangeValid) return;
        _checkShowDel();
        controller.onChange?.call(text);
      },
      onEditingComplete: () {
        controller.controller.clearComposing();
        controller.focusNode.unfocus();
        controller.onSubmit?.call(controller.controller.text);
      },
      controller: widget.controller.controller,
      focusNode: widget.controller.focusNode,
      style: TextStyle(fontSize: widget.fontSize, color: widget.color ?? Colors.black, fontWeight: widget.fontWeight),
      inputFormatters: widget.inputFormatters,
      textInputAction: widget.textInputAction,
      keyboardType: widget.keyboardType,
      obscureText: widget.obscureText,
      maxLines: widget.maxLines,
      minLines: widget.minLines,
      textAlign: widget.textAlign,
    );
  }
}

///输入控制器
class InputController {
  final ValueChanged<String>? onSubmit;
  final ValueChanged<String>? onChange;
  final bool autoFocus;
  final TextEditingController controller = TextEditingController();
  final FocusNode focusNode = FocusNode();

  InputController({
    this.onSubmit,
    this.onChange,
    this.autoFocus = true,
  });

  void cleanInput() {
    controller.clear();
    onSubmit?.call("");
    onChange?.call("");
  }

  void dispose() => controller.dispose();

  set text(String value) => controller.text = value;

  void addListener(VoidCallback listener) => controller.addListener(listener);

  String get text => controller.text;
}
